<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>C++ Tutorial Small Programs</title>
  <meta
 content="C++ Tutorial: Small Programs"
 name="description" />
  <meta
 content="C++ Tutorial, Small Programs, strlen(), strcpy(), memcpy()"
 name="keywords" />
  <meta http-equiv="Content-Type"
 content="text/html; charset=ISO-8859-1" />
  <link type="text/css" rel="stylesheet" href="../images/bogostyleWidePre.css" />
</head>
<body>nonre
<div id="page" align="center">
<div id="content" style="width: 800px;">
<div id="logo">
<div class="whitetitle" style="margin-top: 70px;">bogotobogo </div>
</div>
<div id="topheader">
<div class="headerbodytext" align="left"><br />
<strong>Bogotobogo</strong><br />
contact@bogotobogo.com </div>
<div class="smallgraytext" id="toplinks"><a href="../index.html">Home</a>
| <a href="../sitemap.html">Sitemap</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="menu">
<div class="smallwhitetext" style="padding: 9px;" align="right"><a
 href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">Products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="submenu">
<div class="smallgraytext" style="padding: 9px;" align="right">
<a href="../gif.html">Gif</a> 
|<a href="../java_applet.html">JavaApplet/Web Start</a>
| <a href="../flash.html">Flash</a>
| <a href="../shockwave.html">ShockWave</a>
| <a href="../svg.html">SVG</a>
| <a href="../iPhone.html">iPhone/iPad</a>
| <a href="../android.html">Android</a>
| <a href="../OnHTML5.html">HTML5</a>
| <a href="../Algorithms/algorithms.html">Algorithms</a>
| <a href="../News/NewsMain.html">News</a>
| <a href="../cplusplus/cpptut.html">C++</a>
| <a href="../Java/tutorial/on_java.html">Java</a>
| <a href="../php/phptut.html">PHP</a>
| <a href="../DesignPatterns/introduction.html">Design Patterns</a>
| <a href="../python/pytut.html">Python</a> 
| <a href="../CSharp/.netframework.html">C#</a>
| <a href="../forums.html">Forums</a> 
| <a href="../VisualBasicSQL/introduction.html">Visual Basic</a>
</div>
</div>


<div id="contenttext">
<br />
<br />
<!-- Use of this code assumes agreement with the Google Custom Search Terms of Service. -->
<!-- The terms of service are available at http://www.google.com/cse/docs/tos.html -->
<form name="cse" id="searchbox_demo" action="http://www.google.com/cse">
  <input type="hidden" name="cref" value="" />
  <input type="hidden" name="ie" value="utf-8" />
  <input type="hidden" name="hl" value="" />
  <input name="q" type="text" size="40" />
  <input type="submit" name="sa" value="Search" />
</form>
<script type="text/javascript" src="http://www.google.com/cse/tools/onthefly?form=searchbox_demo&lang="></script>


<div id="bookmarkshare">
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;username=khhong7"><img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=khhong7"></script>
</div>



<br />


<div style="padding: 10px;"><span class="titletext">C++ Tutorial: Small Programs</span></div>

<img src="../images/cplusplus/cpp_logo.jpg" alt="cplusplus logo"/>

<br />
<br />
<div class="bodytext" style="padding: 12px;" align="justify"> 
<div class="subtitle_2nd" id="SubList">List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a></li> 
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II - void*, Pointer/Array, and Pointer to Pointer</a></li>
   <li><a href="pointers3.html">Pointers III - Pointer to Function, Null Pointer</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
</div>

<br /><br />
<img src="images/smallprograms/ChunSooMan.png" alt="ChunSooMan"/>
<br /><br />


<div class="bodytext" style="padding: 12px;" align="justify"> 
<div class="subtitle_2nd" id="SubList">List of Small C++ Programs in This Chapter</div>
<ul>
   <li> <a href="#bitcount">Counting Bits in an Unsigned Integer</a> </li>
   <li> <a href="#strlen">int strlen(const char *)</a> </li>
   <li><a href="#strcpy">char* strcpy(char *, const char*)</a> </li>
   <li><a href="#memcpy">void * memcpy ( void * destination, const void * source, size_t sz)</a> </li>
   <li><a href="#memmove">void *memmove(void *dest, const void *src, size_t sz)</a> </li>
   <li><a href="#memset">void * memset ( void * destination, int source, size_t sz )</a></li> 
   <li><a href="#str2int">Converting String to Integer (atoi())
</a></li> 
   <li><a href="#int2str">Converting Integer to String (itoa())</a></li> 
   <li><a href="#atof">ASCII String to Float - atof()</a></li> 
   <li><a href="#strreverse">Reversing a String</a></li> 
   <li><a href="#nonrepeata">Finding the First Un-repeating (Non-repeating) Character - A</a></li> 
   <li><a href="#nonrepeatb">Finding the First Un-repeating (Non-repeating) Character - B</a></li> 
   <li><a href="#binarysearcha">Binary Search A</a></li> 
   <li><a href="#binarysearchb">Binary Search B - Recursive</a></li> 
   <li><a href="#endian">Big endian or Little endian</a></li> 
   <li><a href="#hashtable">Hash Table Based on K & R</a></li> 
   <li><a href="#calculator">Calculator Based on K & R</a></li> 
   <li><a href="#sizeofstruct">Size of struct</a></li> 
   <li><a href="#removeleftspace">Removing Left Space of a String</a></li> 
</ul>
</div>

<br /><br />
<img src="images/smallprograms/AnMyunDo.png" alt="AnMyunDo"/>
<br /><br />


<div class="bodytext" style="padding: 12px;" align="justify"> 
<div class="subtitle_2nd" id="bitcount">Counting Bits in an Unsigned Integer</div>
<p>Computing the number of 1-bits in an unsigned integer:
</p>
<pre>
/* Counting the Bit Set for an Unsigned Integer */
/*
(A) Loop through all the bits
    Computing time is proportional to the number of bits
(B) Computing time is proportional to the number of bits set
*/

#include &lt;iostream&gt;

using namespace std;


/* bit count for unsigned integer */
/* checking if the first bit == 1 while shifting right
   (25) 
   11001 -> 1100 -> 110 -> 11 -> 1
*/

int bit_countA(unsigned int n){
	int count = 0;
	while(n) {
		count += n & 0x1u;
		n >>= 1;		
	}
	return count;
}


/* sets the right most bit set 1 to 0 */
/* Computing time is proportional to the number of bits set */

int bit_countB(unsigned int n) {
	int count = 0;
	while(n) {
		count ++;
		n &= n - 1;		
	}
	return count;
}

int main()
{
	/* 25 (11001) */
	unsigned int num = 25;

	cout << num <<": # of bits set (A) is " << bit_countA(num) << endl;
	cout << num <<": # of bits set (B) is " << bit_countB(num) << endl;

	return 0;
}
</pre>


<br />
<br />
<div class="subtitle_2nd" id="strlen">int strlen(const char *)</div>
<p><strong>strlen()</strong> counts just the visible characters and not the null character.</p>
<pre>
int strlen1(const char *s) {
    int n=0;
    while (*s++) n++;
    return(n);
}

int strlen2(const char *s) {
    int n=0;
    while (s[n]) n++;
    return(n);
}
</pre>
<br />
<br />

<div class="subtitle_2nd" id="strcpy">char* strcpy(char *, const char*)</div>
<pre>
char* strcpy1(char s1[], const char s2[]) {
	for(int i=0; i <=strlen(s2); i++) {
		s1[i] = s2[i];
	}
	return s1;
}

char* strcpy2(char *s1, const char *s2) {
	char *p = s1;
	while(*s2!='\0') {
		*s1 = *s2;
		s1++;
		s2++;
	}
        *s1 = '\0';
	return p;
}

char* strcpy3(char *s1, const char *s2) {
	char *p = s1;
	while(*s2) *s1++ = *s2++;
        *s1 = '\0';
	return p;
}

char* strcpy4(char *s1, const char *s2) {
	char *p = s1;
	while(*s1++ = *s2++);
	return p;
}


char* strcpy5(char *s1, const char *s2) {
	int i = 0, j = 0;
	while(s1[i++] = s2[j++]);
	return s1;
}
</pre>

<br />
<br />

<div class="subtitle_2nd" id="memcpy">void * memcpy ( void * destination, const void * source, size_t sz );
</div>
<p><strong>Copy block of memory</strong><br />
Copies the values of <strong>sz</strong> bytes from the location pointed by <strong>source</strong> directly to the memory block pointed by <strong>destination</strong>.<br />
The underlying types of the objects pointed by both the <strong>source</strong> and <strong>destination</strong> pointers are irrelevant for this function;<br />
 The result is a <strong>binary (bit pattern)</strong> copy of the data.<br />
The function does not check for any terminating null character in <strong>source</strong> - it always copies exactly <strong>sz</strong>  bytes.<br />
The behavior of <strong>memcpy()</strong> is undefined if <strong>source</strong>  and <strong>destination</strong> overlap.
</p>
<pre>
#include &lt;iostream&gt;
using namespace std;

void *memcpy( void *destination, const void *source, size_t sz ) {
  char *dest = (char *)destination;
  char const *src = (char *)source;

  while (sz--)
    *dest++ = *src++;
  return destination;
}

int main()
{
	char src1[] = "Ludwig Van Beethoven";
	char *src2 = "Franz Liszt ";
	char dest[40];

	cout << "src 1: " << src1 << endl;
	memcpy(dest,src1, strlen(src1)+1);
	cout << "dest: " << dest<< endl;

	cout << "src 2: " << src2 << endl;
	memcpy(dest,src2, strlen(src2)+1);
	cout << "dest: " << dest<< endl;

	return 0;
}
</pre>
<p>Output is:</p>
<pre>
src 1: Ludwig Van Beethoven
dest: Ludwig Van Beethoven
src 2: Franz Liszt
dest: Franz Liszt
</pre>


<br />
<br />

<div class="subtitle_2nd" id="memmove">void *memmove(void *dest, const void *src, size_t sz)
</div>
<p><strong>Memmove()</strong> copies n bytes between two memory areas; unlike with <strong>memcpy()</strong> the areas may overlap. Actually, it is a variant of <strong>memcpy()</strong> that allows the source and destination block to overlap; otherwise it is equivalent (but slightly slower). 
</p>

<pre>
#include &lt;iostream&gt;
using namespace std;

void *memcpy(void *dest, const void *src, size_t sz)
{
	char *tmp = (char *)dest;
	char *s = (char *)src;

	while(sz--) {
		*tmp++ = *s++;
	}
	return dest;
}

void *memmove(void *dest, const void *src, size_t sz)
{
	char *tmp, *s;

	if (dest <= src) {
		tmp = (char *) dest;
		s = (char *) src;
		while (sz--)
			*tmp++ = *s++;
		}
	else {
		tmp = (char *) dest + sz;
		s = (char *) src + sz;
		while (sz--)
			*--tmp = *--s;
		}

	return dest;
}

int main()
{
	char src[50] = "Einstein was a very nice person!";

	cout << src << endl;
	memmove(src + 20, src + 15, 17);
	cout << src << endl;

	return 0;
}
</pre>
<p>Output is:</p>
<pre>
Einstein was a very nice person!
Einstein was a very very nice person!
</pre>
<br />
<br />



<div class="subtitle_2nd" id="memset">void * memset ( void * destination, int source, size_t sz );
</div>
<p>
Sets the first <strong>sz</strong> bytes of the block of memory pointed by <strong>destination</strong> to the specified <strong>source</strong> (interpreted as an unsigned char). </p>
<pre>
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

void *MyMemset(void* destination, int source, size_t sz)
{
	char *pt = (char *)destination;
	while(sz--) {
	     *pt++ = (unsigned char)(source);
	}
	return destination;
}
 
int main()
{
	char str1[]  = "What the heck is memset?";
	char str2[]  = "What the heck is memset?";
	memset(str1 + 5, '*',8);
	puts(str1);
	MyMemset(str2 + 5, 'x',8);
	puts(str2);
	return 0;
}
</pre>
<p>Output is:</p>
<pre>
What ******** is memset?
What xxxxxxxx is memset?
</pre>

<br />
<br />


<div class="subtitle_2nd" id="str2int">Converting String to Integer (atoi())
</div>
<p><strong>example A</strong></p>
<pre>
#include &lt;sstream&gt;
int str2intA(const string &str) {
       stringstream ss(str);
	int n;
	ss >> n;
	return n;
}
</pre>
<br />
<p><strong>example B</strong></p>
<pre>
int str2intB(const string &str){
	int n = 0;
	int len =str.length();
	for(int i = 0; i < len; i++) {
		n *= 10;
		n += str[i]-'0';
	}
	return n;
}
</pre>

<br />
<br />

<div class="subtitle_2nd" id="int2str">Converting Integer to String (itoa())
</div>
<p><strong>example A</strong></p>
<pre>
#include &lt;sstream&gt;
string int2strA(int n) {
	stringstream ss;
	ss << n;	
	return ss.str();
}
</pre>
<br />
<p><strong>example B</strong></p>
<pre>
string int2strB(int numb) {
	int i=0;
	int end=10;
	char* temp = new char[end];
	
	//store one digit at a time 
	for(i = 0; numb > 0; i++) {
		temp[i] = (numb % 10) + '0';
		numb /= 10;
	}

	// temp has the number in reverse order
	int len = i;
	int ii = 0;
	string s = new char[len];
	while(i > 0) s[ii++] = temp[--i];
	s.erase(len);
	delete temp;
	return s;
}
</pre>
<br />
<p><strong>example C</strong></p>
<pre>
#include &lt;iostream&gt;
#include &lt;cstring&gt;

using namespace std;

// reverse the string
void reverse(char *s)
{
	int sz = strlen(s);
	char c;
	int i, j;
	for(i = 0, j = sz -1; i < j; i++, j--) {
		c = s[i];
		s[i] = s[j];
		s[j] = c;
	}
}

// itoa
void int2strC(int n, char *s)
{
	int i = 0;
	while( n ) {
		s[i++] =  n % 10 + '0';
		n /= 10;
	}
	s[i] = '\0';
	cout << "before the reverse s = " << s << endl;
	reverse(s);
}

int main()
{
	char s[10];
	int n = 987654321;
	cout << "input n = " << n << endl;
	int2strC(n, s);
	cout << "output s = " << s << endl;
	return 0;
}
</pre>
<p>Output from the run:</p>
<pre>
input n = 987654321
before the reverse s = 123456789
output s = 987654321
</pre>
<br />
<br />

<div class="subtitle_2nd" id="atof">ASCII String to float - atof()</div>
<pre>
#include &lt;iostream&gt;
using namespace std;

double atofA(char s[]) 
{
	double d = 0, power = 1;
	int sign = 1;
	int i = 0;

	if(s[i] == '-' ) sign = -1;
	i++;
	while(s[i]) {
		if(s[i] == '.') break;
		d = d * 10 + (s[i] - '0');
		i++;
	}
	i++;
	power = 0.1;
	while(s[i]) {
		d += (s[i] - '0')*power;
		power /= 10.0;
		i++;
	}

	return d*sign;
}

int main()
{
	double d = atofA("-314.1592");
	cout.precision(7);
	cout  << d << endl;
	return 0;
}
</pre>
<br />
<br />


<div class="subtitle_2nd" id="strreverse">Reversing a String</div>
<p><strong>Example A</strong></p>
<pre>
#include &lt;iostream&gt;
#include &lt;cstring&gt;

void reverse_string(char s[]) {
	int i,j,c;
	for(i = 0, j = strlen(s)-1; i < j ; i++, j-- ) {
		c = s[i];
		s[i] = s[j];
		s[j] = c;
	}
}

int main() {
	char s[] ="reverse me";
	reverse_string(s);
	std::cout << s << std::endl;
	return 0;
}
</pre>
<br />
<p><strong>Example B Printing a String Reversed </strong><br />
Here we have two print functions, one for normal and the other one for printing a string in reverse.
</p>
<pre>
#include &lt;iostream&gt;

using namespace std;

void normalPrint(char *s)
{
	if(*s) {
		putchar(*s);
		normalPrint(s+1);
	}
}
void reversePrint(char *s)
{
	if(*s) {
		reversePrint(s+1);
		putchar(*s);
	}
}

int main() 
{
	char *str = "Normal or Reverse";
	normalPrint(str);
	cout << endl;
	reversePrint(str);
	cout << endl;
	return 0;
}
</pre>
<p>Output is:</p>
<pre>
Normal or Reverse
esreveR ro lamroN
</pre>

<br />
<br />
<div class="subtitle_2nd" id="nonrepeata">Finding the First Un-repeating (Non-repeating) Character - Method A</div>
<p>This code is using map. <br />
<ol>
	<li>Put all characters into a map.</li>
	<li>If necessary (repeated), it will increment a counter which is the 2nd component of map, value.</li>
	<li>Then, traverse the string and search the map. If found and counter value is 1, return that character.</li>
	<li>Complexity: traversing (O(N)), searching balanced binary tree (O(log(N)) => O(N + log(N)) => O(N) </li>
</ol>
<pre>
// Returning a character which is the first non-repeated in a string
#include &lt;iostream&gt;
#include &lt;string&gt;
#include &lt;map&gt;

using namespace std;
char find(string s)
{
	map&lt;char,int&gt; myMap;
	int len = s.length();
	for(int i = 0; i < len; i++) ++myMap[s[i]];
	for(int i = 0; i < len; i++) 
		if(myMap.find(s[i])->second == 1) return s[i];

	return 0;
}

int main()
{
	string s="abudabi";
	cout << find(s);
	return 0;
}
</pre>
<br />
<br />

<div class="subtitle_2nd" id="nonrepeatb">Finding the First Un-repeating (Non-repeating) Character - Method B</div>
<p>This method is using simple array utilizing the inversion of character and integer.</p>
<p>Complexity: O(N) - It needs just two traversing.</p>
<pre>
// Returning a character which is the first non-repeated in a string
#include &lt;iostream&gt;
#include &lt;string&gt;
using namespace std;

char find(string s)
{
	int myArr[256] = {0};
	int len = s.length();
	for(int i = 0; i < len; i++) 
		myArr[static_cast&lt;int&gt;(s[i])]++;

	for(int i = 0; i < len; i++)
		if(myArr[static_cast&lt;int&gt;(s[i])] == 1) return s[i];

	return 0;
}

int main()
{
	string s="abudabi";
	cout << find(s);
	return 0;
}
</pre>
<br />
<br />

<div class="subtitle_2nd" id="binarysearcha">Binary Search A</div>
<pre>
#include &lt;iostream&gt;

using namespace std;

int bsearch(int [], int, int, int);

int main()
{
	const int arrSize = 100;
	int arr[arrSize];

	for (int i = 0; i <= arrSize -1; i++) {
		arr[i] = i;
	}

	int x = 35;
	int low = 0;
	int high = arrSize -1;
	int found = bsearch(arr, x, low, high);
	if(found == -1) {
		cout << "Could not find " << x << endl;
		return 0;
	}
	cout << "The value " << x << " is at " << found << endl;
	return 0;
}

int bsearch(int arr[], int x, int low, int high) {
	int mid;
	if(high < low) return -1;  // no match 
	while (low <= high) {
		mid = low + (high - low) / 2;
		if(x < arr[mid])
			high = mid - 1;
		else if (x > arr[mid])
			low = mid + 1;
		else
			return mid;	// this is match 
	}
}
</pre>
<br />
<br />


<div class="subtitle_2nd" id="binarysearchb">Binary Search B - Recursive</div>
<pre>
int bsearch(int arr[], int x, int low, int high) {
	int mid;
	if(high < low) return -1;  // no match 
	mid = low + (high - low) / 2;
	if(x < arr[mid]) 
		bsearch(arr, x, low, mid - 1);
	else if (x > arr[mid]) 
		bsearch(arr, x, mid + 1, high);
	else
		return mid;	// this is match 
}
</pre>
<br />
<br />

<div class="subtitle_2nd" id="endian">Big endian or Little endian?</div>
<p>Endian is important to know when reading or writing data structures, especially across networks so that different application can communicate with each other. Sometimes the endianness is hidden from the developer. Java uses a fixed endianness to store data regardless of the underlying platform's endianness, so data exchanges between two Java applications won't normally be affected by endianness. But other languages, C in particular don't specify an endianness for data storage, leaving the implementation free to choose the endianness that works best for the platform.</p>
<br />
<img src="images/smallprograms/endian_diagram.png" alt="endian_diagram"/>
<br />
<br />
<p>The picture below is a diagram for the example to check if a machine is little endian or big endian. The box shaded blue is the the byte we are checking because it's where a one-byte type (char) will be stored. The diagram shows where an integer (4-byte) value <strong>1</strong> is stored.</p>
<br />
<img src="images/smallprograms/checking_little_big_endian.png" alt="checking_little_big_endian"/>

<br />
<br />
<p><strong>Source A</strong>
<pre>
#include &lt;iostream&gt;
using namespace std;

/* if the dereferenced pointer is 1, the machine is little-endian 
   otherwise the machine is big-endian */

int endian() {
	int test = 1;
	char *ptr;
	ptr = (char *)&test;
	return (*ptr);
}

int main()
{
	if(endian()) 
		cout << "little endian\n";
	else
		cout << "big endian\n";
}
</pre>
<br />

<p><strong>Source B</strong>
<pre>
#include &lt;iostream&gt;
using namespace std;

int endian() {
	union {
		int one;
		char ch;
	} endn;

	endn.one = 1;
	return endn.ch;
}

int main()
{
	if(endian()) 
		cout << "little endian\n";
	else
		cout << "big endian\n";
}
</pre>
<br />
<br />
<br />

<div class="subtitle_2nd" id="hashtable">Hash Table Based on K & R</div>
<pre>
#include &lt;iostream&gt;
using namespace std;

#define HASHSIZE 101

struct nlist {       /* table entry: */
       struct nlist *next;   /* next entry in chain */
       char *name;           /* defined name */
       char *defn;           /* replacement text */
};

static struct nlist *hashtab[HASHSIZE];

unsigned hash(char *s) {
       unsigned hashval;

       for (hashval = 0; *s != '\0'; s++)
           hashval = *s + 31 * hashval;
       return hashval % HASHSIZE;
}

struct nlist *lookup(char *s) {
       struct nlist *np;

       for (np = hashtab[hash(s)];  np != NULL; np = np->next)
           if (strcmp(s, np->name) == 0)
               return np;     /* found */
       return NULL;           /* not found */
}

/* install:  put (name, defn) in hashtab */
struct nlist *install(char *name, char *defn) {
       struct nlist *np;
       unsigned hashval;

       if ((np = lookup(name)) == NULL) { /* not found */
		   np = new nlist;
           if (np == NULL || (np->name = _strdup(name)) == NULL)
               return NULL;
           hashval = hash(name);
           np->next = hashtab[hashval];
           hashtab[hashval] = np;
       } else       /* already there */
           /*free previous defn */
		   delete np->defn;
       if ((np->defn = _strdup(defn)) == NULL)
           return NULL;
       return np;
}

/* uninstall:  take (name, defn) out of hashtab */
int undef(char * name) {
	struct nlist * np1;
	/* name not found */
	if ((np1 = lookup(name)) == NULL)  
		return 1;

	/* name found */
	if((np1 = hashtab[hash(name)]) != NULL ) {
		hashtab[hash(name)] = np1->next;
		delete np1;
		return 0;
	}
	/* name not found */
	return 1;  
}

void print() {

	struct nlist *np;
	for(int i = 0; i < HASHSIZE; i++) {
		np = hashtab[i];
		if(np) 
			cout << np->name << "-->" << np->defn << " ";
	}
	cout << endl;
}

int main()
{
	install("A","65");
	install("B","66");
	install("C","67");
	install("D","68");
	install("E","69");
	print();
	undef("C");
	print();
	undef("B");
	print();
	return 0;
}
</pre>
<p>Output from the run:</p>
<pre>
A-->65 B-->66 C-->67 D-->68 E-->69
A-->65 B-->66 D-->68 E-->69
A-->65 D-->68 E-->69
</pre>

<br />
<br />

<div class="subtitle_2nd" id="calculator">Calculator Based on K & R</div>
<pre>
/* Calculator based on K & R
  (1) Not working for '(' such as 1+(5-3) 
  (2) Added 
		getop(s);
		push(a2f(s));
	after '+', '-', '*', and '/' to push next number
*/

#include &lt;iostream&gt;
#include &lt;cstring&gt;
#include &lt;cctype&gt;

using namespace std;

int getop(char []);
void push(double);
double pop(void);
int getch(void);
void ungetch(int);
int a2f(char *);
void calc();

int main() 
{
	calc();
	return 0;
}

const int MAXOP = 100;
const char NUMBER = '0';

void calc() {
	int type;
	double op2;
	char s[MAXOP];
	 
	while((type = getop(s)) != EOF) {
		switch (type) {
			case NUMBER:
				push(a2f(s));
				break;
			case '+':
				getop(s);
				push(a2f(s));
				push(pop() + pop());
				break;
			case '*':
				getop(s);
				push(a2f(s));
				push(pop() * pop());
				break;
			case '-':
				getop(s);
				push(a2f(s));
				op2 = pop();
				push(pop()-op2);
				break;
			case '/':
				getop(s);
				push(a2f(s));
				op2 = pop();
				if(op2 != 0.0) 
					push(pop() / op2);
				else
					cout << "error: division by zero" << endl;
				break;
			case '\n':
				cout << pop() << endl;
				break;
			default:
				cout << "error: unknown command " << s << endl;
		}
	}
}

// getop(): get next operator or numeric operand 
int getop(char s[]) {
	int i, c;

	while ( (s[0] = c = getch()) == ' ' || c == '\t') 
		;
	s[1] = '\0';
	if( !isdigit(c) && c != '.')
		return c;	// not a number
	i = 0;
	if (isdigit(c))	// collect integer part
		while (isdigit(s[++i] = c = getch()))
			;
	if (c == '.')	// collect fraction
		while (isdigit(s[++i] = c = getch()))
			;
	s[i] = '\0';
	if (c != EOF )
		ungetch(c);

	return NUMBER;
}

const int BUFSIZE = 100;
char buf[BUFSIZE];
int bufp = 0;

int getch(void) {
	return (bufp > 0) ? buf[--bufp] : cin.get();
}

void ungetch(int c) {
	if (bufp >= BUFSIZE)
		cout << "ungetch(): too many characters\n";
	else
		buf[bufp++] = c;
}

int a2f(char *s) {
	int n = 0;
	while(*s) {
		n *= 10;
		n += (*s++)-'0';
	}
	return n;
}

const int MAXVAL = 100;
int sp = 0;
double val[MAXVAL];

void push(double f) {
	if( sp < MAXVAL )
		val[sp++] = f;
	else
		cout << "error: stack full, can't push "<< f << endl;
}

double pop(void) {
	if (sp > 0)
		return val[--sp];
	else {
		cout << "error: stack empty \n";
		return 0.0;
	}
}
</pre>
<br />
<br />

<div class="subtitle_2nd" id="sizeofstruct">Size of struct</div>
<p>How do we find the number of structures for the given array of structures in the sample code below?</p>
<p>
<pre>
#include &lt;iostream&gt;

using namespace std; 

struct vehicle
{
	int price;
	char type[10];
} car[] =
{
	{1,"a"},{2,"b"},{3,"c"}
};

int main() 
{
	cout << "sizeof(car)=" << sizeof(car) << endl;
	cout << "sizeof(*car)=" << sizeof(*car) << endl;
	cout << "sizeof(car)/sizeof(*car)=" << sizeof(car)/sizeof(*car) << endl;
	return 0;
}
</pre>
<p>Answer is:</p>
<pre>
sizeof(car)=48
sizeof(*car)=16
sizeof(car)/sizeof(*car)=3
</pre>
<p>Note that the size of an array of <strong>vehicle</strong> struct is not <strong>4+1*10</strong> but <strong>16</strong>. 
This is probably due to <strong>padding/allignmment</strong>: </p>
<pre>
4 + 1*4 + 1*4 + (1*2+<font color="blue">2</font>) = 16
</pre>
<p>As an exercise, how about the following example:</p>
<pre>
struct StructA 
{ 
	char ch1; 
	char ch2; 
	int n; 
}; 

struct StructB 
{ 
	char ch1; 
	int n; 
	char ch2; 
}; 

int sizeA = sizeof(StructA); // sizeA = 1 + 1 + <font color="blue">(2-padding)</font> + 4 = 8
int sizeB = sizeof(StructB); // sizeB = 1 + <font color="blue">(3-padding)</font> + 4 + 1 + <font color="blue">(3-padding)</font> = 12
</pre>
<p>
Remember, it is frequently very difficult to predict the sizes of compound datatypes such as a <strong>struct</strong> or <strong>union</strong> due to structure <strong>padding</strong>. Another reason for using <strong>sizeof</strong> is <strong>readability</strong>.</p>
<br />
<br />

<div class="subtitle_2nd" id="removeleftspace">Removing Left Space of a String</div>
<pre>
#include &lt;iostream&gt;
#include &lt;cassert&gt;

using namespace std; 

char *left_space_trim(char *buf, const char *s) {
	assert(buf != NULL);
	assert( s!= NULL);

	while(isspace(*s))
		s++;
	strcpy(buf,s);
	return buf;
}

int main() 
{
	char *srcStr = strdup("  String with left_side spaces");
	char *dstStr = (char*)malloc(strlen(srcStr)+1);
	cout << srcStr << "=>" << left_space_trim(dstStr,srcStr) << endl;

	return 0;
}
</pre>
<p>Output is:</p>
<pre>
  String with left_side spaces=>String with left_side spaces
</pre>
<br />
<br />
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a></li> 
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>

<br />
<img src="images/smallprograms/song.png" alt="Song, Heykyo"/>
<br />
<div id="rightpanel">
<div align="center">
</div></div>
<br />

<br />
</div>

<br />
<br />
<br />



<div class="smallgraytext" id="footer"><a href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="#">Contact Us</a>
| Bogotobogo &copy; 2011 | <a target="_blank" href="http://www.bogotobogo.com">Bogotobogo </a></div>
</div>
</div>
</body>
</html>
